package xyz.yuanjilu.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializableUtils {
	
	public static byte[] serialize(Serializable value) {
		  try {
		      //序列化核心就是ByteArrayOutputStream
		    ByteArrayOutputStream bos = new ByteArrayOutputStream();
		    ObjectOutputStream oos = new ObjectOutputStream(bos);
		    oos.writeObject(value);
		    oos.flush();
		    oos.close();
		    return bos.toByteArray();
		  } catch (Exception e) {
		    throw new RRException("Error serializing object.  Cause: " + e, e);
		  }
	}
	public static Serializable deserialize(byte[] value) {
		return deserialize(value, Serializable.class);
	 }
	public static <T> T deserialize(byte[] value,Class<T> returnType) {
		   T result;
		   try {
		       //反序列化核心就是ByteArrayInputStream
		     ByteArrayInputStream bis = new ByteArrayInputStream(value);
		     ObjectInputStream ois = new ObjectInputStream(bis);
		     result = (T) ois.readObject();
		     ois.close();
		   } catch (Exception e) {
		     throw new RRException("Error deserializing object.  Cause: " + e, e);
		   }
		   return result;
	 }
}
